const express = require('express')
const userRouter = express.Router()
const { uploadToken } = require('../model/qiniuConfig')
const { genRule, saveUserSession } = require('../utils/handleUser')
const userModel = require('../model/userSchema')
const bcrypt = require('bcrypt')
const passport = require('passport')
const jwt = require('jsonwebtoken')

userRouter.post('/register', async(req, res) => {
    //获取前端发送过来的值
    let { nick_name, password, email, identity } = req.body

    //数据库里去查找对应的值
    let searResult = await userModel.findOne({ $or: [{ nick_name }, { email }] })

    if (searResult) {
        //失败的时候 数据库里有值
        res.send({ code: 1, errInfo: '用户名或者密码已经存在' })
    } else {
        //成功数据库里没有值
        //1.进行密码加密
        let salt = await bcrypt.genSalt(10)
        let genPassword = await bcrypt.hash(password, salt)
            //2.吧加密后的密码进行保存
        let saveResult = await userModel.create({ nick_name, password: genPassword, email, identity })
            //3.生成一个签名
        let token = await jwt.sign(genRule(saveResult), 'kiss', { expiresIn: 3600 })

        //前端拿到数据值
        req.session.userInfo = saveUserSession(saveResult)

        // console.log(req.session.userInfo);

        //返回给前端
        res.json({
            code: 0,
            token: `Bearer ${token}`,
            msg: '注册成功'
        })
    }
})

userRouter.post('/login', async(req, res) => {
    //做验证
    //获取前端传来的值
    let { password, email } = req.body
        //去数据库查找对应的邮箱
    let searResult = await userModel.findOne({ email })
        //如果数据库里面没有返回给前端没有此用户
    if (!searResult) {
        res.send({ code: 1, errInfo: '没有该用户' })
    } else {
        //如果数据库里面有对应的邮箱，此时对密码进行判读
        let genPassword = searResult.password
        let checkStatus = await bcrypt.compare(password, genPassword)
        let token = await jwt.sign(genRule(searResult), 'kiss', { expiresIn: 3600 })

        //存储用户的登陆次数
        await userModel.updateOne({ _id: searResult._id }, { loginNum: ++searResult.loginNum })
        req.session.userInfo = saveUserSession(searResult)

        if (checkStatus) {
            res.json({
                code: 0,
                token: `Bearer ${token}`,
                errInfo: '登陆成功'
            })
        } else {
            res.json({
                code: 1,
                errInfo: '密码错误'
            })
        }
    }
})

//用户上传头像到七牛
userRouter.get('/getToken', passport.authenticate('jwt', { session: false }),
    async(req, res) => {
        let token = uploadToken()
        res.send({ code: 0, msg: token, data: req.user })
            // res.end()
    })

//修改用户签名 头像 博客地址

userRouter.post('/addInfo', passport.authenticate('jwt', { session: false }), async(req, res) => {
    Object.keys(req.body).forEach(key => {
        if (req.user[key] === req.body[key]) {
            return
        }
        req.user[key] = req.body[key]
        req.session.userInfo[key] = req.body[key]
    })

    await userModel.updateOne({ 'nick_name': req.user.nick_name }, req.user)
    res.send({ code: 0, msg: '添加成功' })
})

//修改用户密码
userRouter.post('/updatePassword', passport.authenticate('jwt', { session: false }), async(req, res) => {
    let { newPassword, password } = req.body

    let checkStatus = await bcrypt.compare(password, req.user.password)



    if (checkStatus) {
        let salt = await bcrypt.genSalt(10)
        let genPassword = await bcrypt.hash(newPassword, salt)
        let saveResult = await userModel.updateOne({ 'nick_name': req.user.nick_name }, { $set: { password: genPassword } })

        if (saveResult) {
            res.send({ code: 0, errorInfo: '修改成功' })
        }
    } else {
        res.send({ code: 1, errorInfo: '旧密码错误' })
    }
})



module.exports = userRouter